package pers.qianyu.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.qianyu.module.core.comm.Pagination;
import pers.qianyu.module.core.domain.system.converter.SysResourceConverter;
import pers.qianyu.module.core.domain.system.entity.SysResourcePO;
import pers.qianyu.module.core.domain.system.query.SysResourceQuery;
import pers.qianyu.module.core.domain.system.vo.SysResourceVO;
import pers.qianyu.module.system.dao.SysResourceDao;
import pers.qianyu.module.system.exception.SysErrorCodeEnum;
import pers.qianyu.module.system.exception.SysException;
import pers.qianyu.module.system.service.SysResourcesService;

import java.util.Comparator;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author mizzle rain
 * @date 2021-05-03 22:08
 */
@Service("sysResourcesService")
public class SysResourceServiceImpl
        extends ServiceImpl<SysResourceDao, SysResourcePO>
        implements SysResourcesService {
    @Autowired
    private SysResourceDao sysResourceDao;
    @Autowired
    private SysResourceConverter sysResourceConverter;

    @Override
    public SysResourceVO queryById(Long id) {
        SysResourcePO sysResourcePO = sysResourceDao.selectById(id);
        if (Objects.isNull(sysResourcePO)) {
            throw new SysException(SysErrorCodeEnum.INVALID_RESOURCE_ID);
        }
        return sysResourceConverter.convertToVO(sysResourcePO);
    }

    @Override
    public Pagination<SysResourceVO> query(SysResourceQuery sysResourceQuery) {
        Page<SysResourcePO> page = new Page<>(sysResourceQuery.getPage(), sysResourceQuery.getLimit());
        SysResourcePO sysResourcePO = new SysResourcePO();
        sysResourcePO.setServ(sysResourceQuery.getServ());
        QueryWrapper<SysResourcePO> queryWrapper = new QueryWrapper<>(sysResourcePO);
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("uri");
        Page<SysResourcePO> sysResourcePOPage = sysResourceDao.selectPage(page, queryWrapper);
        return new Pagination<>(
                sysResourcePOPage.getRecords()
                        .stream()
                        .map(sysResourceConverter::convertToVO)
                        .sorted(Comparator.comparing(SysResourceVO::getUri))
                        .collect(Collectors.toList()),
                sysResourcePOPage.getTotal(),
                sysResourcePOPage.getSize(),
                sysResourcePOPage.getCurrent()
        );
    }
}
